# encoding: utf-8

import cv2 as cv
import pytesseract
from PIL import Image
import numpy as np

class AuthCodeUtil:
    def __init__(self):
        pass

    def recognize_text(image):
        # 边缘保留滤波  去噪
        blur = cv.pyrMeanShiftFiltering(image, sp=8, sr=60)
        #cv.imshow('dst', blur)
        # 灰度图像
        gray = cv.cvtColor(blur, cv.COLOR_BGR2GRAY)
        # 二值化
        ret, binary = cv.threshold(gray, 0, 255, cv.THRESH_BINARY_INV | cv.THRESH_OTSU)
        print(f'二值化自适应阈值：{ret}')
        #cv.imshow('binary', binary)
        # 形态学操作  获取结构元素  开操作
        kernel = cv.getStructuringElement(cv.MORPH_RECT, (1, 1))
        bin1 = cv.morphologyEx(binary, cv.MORPH_OPEN, kernel)
        #cv.imshow('bin1', bin1)
        kernel = cv.getStructuringElement(cv.MORPH_OPEN, (1, 1))
        bin2 = cv.morphologyEx(bin1, cv.MORPH_OPEN, kernel)
        #cv.imshow('bin2', bin2)
        # 逻辑运算  让背景为白色  字体为黑  便于识别
        cv.bitwise_not(bin2, bin2)
        #cv.imshow('binary-image', bin2)
        # 识别
        res = cv.resize(bin2, None, fx=5, fy=5, interpolation=cv.INTER_CUBIC)
        # dilation = cv.dilate(bin2, (1,1), iterations=1)
        kernel = np.ones((3, 3), np.uint8)
        dilation = cv.morphologyEx(res, cv.MORPH_OPEN, kernel)
        cv.imshow('dilation', res)
        test_message = Image.fromarray(dilation)
        print(test_message)
        custom_oem_psm_config = '--psm 6 --oem 3'
        print(pytesseract.image_to_string(test_message, config=custom_oem_psm_config))

    @classmethod
    def read(cls,img):
        src = cv.imread(img)
        #cv.imshow('input image', src)
        cls.recognize_text(src)
        cv.waitKey(0)
        cv.destroyAllWindows()
